﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Automation;
using System.Resources;
using System.Windows;

namespace CalcUIA
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        ///  该函数将创建指定窗口的线程设置到前台，并且激活该窗口。键盘输入转向该窗口，并为用户改各种可视的记号。
        ///  系统给创建前台窗口的线程分配的权限稍高于其他线程。 
        /// </summary>
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄</param>
        /// <returns>如果窗口设入了前台，返回值为非零；如果窗口未被设入前台，返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private void button1_Click(object sender, EventArgs e)
        {
            //将“网上纳税申报系统2.0”窗体置于桌面顶层
            Process[] localByName = Process.GetProcessesByName("MAIN");
            SetForegroundWindow(localByName[0].MainWindowHandle);
           
            var desktop = AutomationElement.RootElement; // 先找到根元素，可以认为是桌面 
            // 在桌面的子控件中查找到名字为“网上纳税申报系统2.0”的窗体。
            var taxAssistant = desktop.FindFirst(TreeScope.Children,
                new PropertyCondition(AutomationElement.NameProperty, Properties.Resources.TaxAssistant)
                );
//            Rect rect = taxAssistant.Current.BoundingRectangle;
//            //点击“报”
//            var point = new System.Windows.Point(rect.X + 10, rect.Y + 125);
//            _mouse.Location = point;
//            _mouse.Click();
//            Thread.Sleep(1000);
//            //点击“下载报表”
//            point = new System.Windows.Point(rect.X + 451, rect.Y + 73);
//            _mouse.Location = point;
//            _mouse.Click();
            ClickEvent.ClickLeftMouse(taxAssistant, 10, 125);
            Thread.Sleep(500);
            ClickEvent.ClickLeftMouse(taxAssistant, 451, 73);
            
            AutomationElement liceInfo;
            AutomationElement SysTip;
          
            //判断是否出现弹窗，否，说明网络正常，正在下载数据
            while ((liceInfo = taxAssistant.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                    new PropertyCondition(AutomationElement.NameProperty, Properties.Resources.licenseInfo))
                )) == null && (SysTip = taxAssistant.FindFirst(TreeScope.Descendants,
                    new AndCondition(
                        new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                        new PropertyCondition(AutomationElement.NameProperty, Properties.Resources.SystemTip))
                    )) == null)
            {
                Thread.Sleep(500);
               
            }
            
            //出现“证书信息”窗口，网络正常
            while((liceInfo = taxAssistant.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                    new PropertyCondition(AutomationElement.NameProperty, Properties.Resources.licenseInfo))
                )) != null)
            {
                ClickButton(taxAssistant, Properties.Resources.licenseInfo, "1");
                Thread.Sleep(500);
                
                //网络正常
                while ((liceInfo = taxAssistant.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                    new PropertyCondition(AutomationElement.NameProperty, Properties.Resources.SystemTip))
                )) != null)
                    ClickButton(taxAssistant, Properties.Resources.SystemTip, "2");
                //中途网络异常，弹出“提示”窗口
                while ((liceInfo = taxAssistant.FindFirst(TreeScope.Descendants,
               new AndCondition(
                   new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                   new PropertyCondition(AutomationElement.NameProperty, Properties.Resources.Tip))
               )) != null)
                    ClickButton(taxAssistant, Properties.Resources.Tip, "2");
                Thread.Sleep(500);
                
                //关闭“下载信息”窗口
                ClickButton(taxAssistant, Properties.Resources.DownloadInfo, "3");
            }
            //出现“系统提示”窗口，网络连接异常
            while ((SysTip = taxAssistant.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                    new PropertyCondition(AutomationElement.NameProperty, Properties.Resources.SystemTip))
                )) != null)
            {
                Thread.Sleep(500);
                ClickButton(taxAssistant, Properties.Resources.SystemTip, "2");
                //关闭“下载信息”窗口
                ClickButton(taxAssistant, Properties.Resources.DownloadInfo, "3");
            }
        }

        #region InvokePattern helper
        /// <summary>
        /// Get InvokePattern
        /// </summary>
        /// <param name="element">AutomationElement instance</param>
        /// <returns>InvokePattern instance</returns>
        public static InvokePattern GetInvokePattern(AutomationElement element)
        {
            object currentPattern;
            if (!element.TryGetCurrentPattern(InvokePattern.Pattern, out currentPattern))
            {
                throw new Exception(string.Format("Element with AutomationId '{0}' and Name '{1}' does not support the InvokePattern.",
                    element.Current.AutomationId, element.Current.Name));
            }
            return currentPattern as InvokePattern;
        }

        #endregion

        #region 
        /// <summary>
        /// Click Button
        /// </summary>
        /// <param name="ae">AutomationElement instance</param>
        ///  <param name="name">window name</param>
        ///  <param name="id">button id</param>
        private static void ClickButton(AutomationElement ae, String name ,String id)
        {

            var readMesWindow = ae.FindFirst(TreeScope.Descendants,
                new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                    new PropertyCondition(AutomationElement.NameProperty, name))
                );
            // 通过AutomationId得到窗体中的“确定”按钮
            var next = readMesWindow.FindFirst(TreeScope.Descendants,
                    new PropertyCondition(AutomationElement.AutomationIdProperty, id)
                );
            //触发事件
            InvokePattern currentPattern = GetInvokePattern(next);
            currentPattern.Invoke();
        }
        #endregion       
    }
}
